package com.xinyuan.digit.next.subscriber.db.pojo;

import com.xinyuan.digit.next.subscriber.db.util.LambdaUtils;

import java.io.Serializable;
import java.util.Collection;

/**
 * 查询条件封装
 *
 * @author LiuChenghui 2025/10/23 14:21:00
 * @version 1.0
 */
public class Condition implements Serializable {
    private final SFunction<?, ?> column;
    private final Operator operator;
    private final Object value;

    public Condition(SFunction<?, ?> column, Operator operator, Object value) {
        this.column = column;
        this.operator = operator;
        this.value = value;

        // 验证参数
        validate();
    }

    /**
     * 参数验证
     */
    private void validate() {
        // BETWEEN 操作需要数组参数
        if (operator.isBetween()) {
            if (!(value instanceof Object[])) {
                throw new IllegalArgumentException("BETWEEN 操作需要 Object[] 类型的参数");
            }
            Object[] betweenValues = (Object[]) value;
            if (betweenValues.length != 2) {
                throw new IllegalArgumentException("BETWEEN 操作需要两个参数");
            }
        }

        // IN 操作需要集合或数组
        if (operator.isIn()) {
            if (!(value instanceof Collection) && !value.getClass().isArray()) {
                throw new IllegalArgumentException("IN 操作需要 Collection 或数组类型的参数");
            }
        }

        // 其他需要值的操作符
        if (operator.requiresValue() && value == null) {
            throw new IllegalArgumentException("操作符 " + operator + " 需要非空参数值");
        }
    }

    // Getters
    public SFunction<?, ?> getColumn() {
        return column;
    }

    public Operator getOperator() {
        return operator;
    }

    public Object getValue() {
        return value;
    }

    /**
     * 生成SQL条件片段
     */
    public String toSQL(int paramIndex) {
        String columnName = LambdaUtils.column(column);
        return operator.toSQL(columnName, paramIndex);
    }
}
